import {ref} from "vue";
import * as WorkItemsApi from "@/api/biz/workItems/workItems";
import {until} from "@vueuse/core";
import {WorkPlanEnum} from "@/utils/constants";

// 缓存变量
const workItemCache = ref(undefined)
// 数据是否准备好
const isReady = ref(false)
// 正在请求
const isLoading = ref(false)
const loadList = async () => {
    isLoading.value = true
    workItemCache.value = await WorkItemsApi.getAllWorkItemsList()
    isLoading.value = false
    isReady.value = true
}

const getCacheAsync = async () => {
    // 如果正在读取，等待上个读取结束后直接返回。
    if(isLoading.value){
        // console.log('已有其他请求正在读取')
        await until(isReady).toBe(true);
        // console.log("其他请求完毕")
        return workItemCache;
    }
    if(!workItemCache.value){
        await loadList()
        return workItemCache;
    }else {
        return workItemCache;
    }
}

/**
 * 按ID查询
 * @param workItemId
 */
const getWorkItem = (workItemId) => {
    if(!workItemId){
        return {id: workItemId, workContent: '失效事项'}
    }
    if(workItemId===WorkPlanEnum.WORK_OFF){
        // 休息日特别处理
        return {id: WorkPlanEnum.WORK_OFF, workContent: WorkPlanEnum.WORK_OFF_LABEL}
    }
    return workItemCache.value.find(item => item.id === workItemId);
}

/**
 * 获取部门事项
 * @param deptId 部门ID
 * @param onlyWorkDuty 是否只要可排班
 */
const getDeptWorkItemListAsync = async ({deptId}) => {
    const cache = await getCacheAsync();
    // 是否过滤可排班事项
    return cache.value.filter(item => item.deptId.indexOf(deptId)> -1)
}

export const useWorkItemCache = () => {
    if(!workItemCache.value) {
        getCacheAsync()
    }
    return {
        isReady,
        cache: workItemCache,
        getCacheAsync,
        getWorkItem,
        getDeptWorkItemListAsync
    }
}
